package com.mygame.game_server;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * mysql工厂
 */
public final class MysqlSessionFactory {

    private final static Logger logger = LoggerFactory.getLogger(MysqlSessionFactory.class);
    /**
     * mybatis sql 会化工厂
     */
    private static SqlSessionFactory _sqlSessionFactory;

    /**
     * 私有化类默认构造器
     */
    static public void init() {
        try {
            _sqlSessionFactory = (new SqlSessionFactoryBuilder())
                    .build(Resources.getResourceAsStream("mybatisConfig.xml"));

            // 测试链接
            SqlSession tempSession = openSession();
            tempSession.getConnection().createStatement().execute("select -1");
            tempSession.close();
            logger.info("====mysql连接成功=====");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 私有化默认构造器
     */
    private MysqlSessionFactory() {

    }

    static public SqlSession openSession() {
        if (null == _sqlSessionFactory) {
            throw new RuntimeException("sqlSessionFactory 尚未初始化");
        }

        return _sqlSessionFactory.openSession(true);
    }


}
